package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.media.dto.ChannelDto;
import com.heima.media.entity.WmChannel;
import com.heima.media.mapper.WmChannelMapper;
import com.heima.media.service.IWmChannelService;

import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements
        IWmChannelService {
    @Override
    public ResponseResult listByName(ChannelDto dto) {
        IPage<WmChannel> page = new Page<>(dto.getPage(), dto.getSize());

        LambdaUpdateWrapper<WmChannel> query = new LambdaUpdateWrapper<>();
        if (!StringUtils.isEmpty(dto.getName())) {
            query.like(WmChannel::getName, dto.getName());
        }
        IPage<WmChannel> iPage = this.page(page, query);
        long total = iPage.getTotal();
        List<WmChannel> records = iPage.getRecords();
        PageResponseResult<List<WmChannel>> result = new PageResponseResult<>(dto.getPage(), dto.getSize(), total, records);
        return result;
    }

    @Override
    public ResponseResult saveWmChannel(WmChannel wmChannel) {
        /*判断参数是否为空
         * */
        if (wmChannel == null || StringUtils.isEmpty(wmChannel.getName())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
//        根据名字查询
        LambdaUpdateWrapper<WmChannel> query = new LambdaUpdateWrapper<>();
        query.eq(WmChannel::getName, wmChannel.getName());
        int count = this.count(query);
//判断是否存在
        if (count > 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }
        wmChannel.setCreatedTime(new Date());
        this.save(wmChannel);

        return ResponseResult.okResult();
    }
}

